<?php

namespace App\Kuafu\Common\Service;

use Exception;
use Illuminate\Support\Facades\File;
use Kuafu\File\FileUtil;
use OSS\Core\OssException;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

class FileService
{
    /**
     * 转存阿里云oss
     *
     * @param string $originalFile
     * @param string $ossFile
     * @param string $modulePath
     * @return mixed
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws OssException
     * @throws Exception
     */
    public static function transferred(string $originalFile, string $ossFile, string $modulePath = "common")
    {
        try{
            $fileSystem = getFileSystem();
            $localDir   = getTmpDir("/{$modulePath}/" . formatDateYmd(time()));
            if (!$fileSystem->isDirectory($localDir)) {
                $fileSystem->makeDirectory($localDir, 0777, true);
            }
            $suffix    = explode("?", File::extension($originalFile))[0];
            $localFile = vsprintf("{$localDir}/%s.%s", [
                md5($originalFile),
                $suffix
            ]);
            $fileSystem->put($localFile, file_get_contents($originalFile));
            $ossInfo = FileUtil::uploadFile($localFile, $suffix, $ossFile);
            $fileSystem->delete($localFile);
            return $ossInfo["url"];
        }catch (Exception $exception){
            logException("图片转存失败", $exception);
            throw $exception;
        }
    }
}
